package com.mmall.seckill.rabbitMQ.miaosha.receiver;

import com.mmall.seckill.common.Const;
import com.mmall.seckill.common.redis.RedisService;
import com.mmall.seckill.common.redis.keyCode.OrderKey;
import com.mmall.seckill.dao.GoodsDao;
import com.mmall.seckill.domain.OrderInfo;
import com.mmall.seckill.domain.SeckillUser;
import com.mmall.seckill.rabbitMQ.MQConfig;
import com.mmall.seckill.rabbitMQ.miaosha.MiaoshaMessage;
import com.mmall.seckill.service.OrderService;
import com.mmall.seckill.util.JsonUtil;
import com.mmall.seckill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by megan on 2018/7/29.
 * 接收秒杀形象消息
 */
@Slf4j
@Service
public class ReceiverMiaoshaMessage {

    @Resource
    private GoodsDao goodsDao;
    @Resource
    private RedisService redisService;
    @Resource
    private OrderService orderService;

    @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
    public void receiverSeckill(String message){
        MiaoshaMessage msg = JsonUtil.string2obj(message,MiaoshaMessage.class);
        log.info("接收到秒杀消息 : {}",JsonUtil.obj2StringPretty(message));
        SeckillUser user = msg.getUser();
        Long goodsId = msg.getGoodsId();

        /** 秒杀正式开始 **/
        GoodsVo goods = goodsDao.getGoodsVoByGoodsId(goodsId);
        int stock = goods.getStockCount();
        //判断库存
        if(stock <= 0){
            Const.localOverMap.put(goodsId,true);
            log.info("user -> {} , goods -> {} 秒杀商品库存不足",user.getNickname(),goods.getId());
            return;
        }
        // 查询缓存是否有订单
        OrderInfo orderInfoCache = getMiaoshaOrderByUserIdGoodsId(user.getId(),goodsId);
        // 判断是否重复秒杀
        if(orderInfoCache != null){
            log.info("user -> {} , goods -> {} 重复秒杀",user.getNickname(),goods.getId());
            return;
        }
        // 减库存,下订单,写入秒杀订单
        try {
            OrderInfo orderInfo = orderService.miaoshaDb(user,goods);
            log.info("user -> {} , goods -> {} 秒杀到订单信息-> {}",user.getNickname(),goods.getId(),JsonUtil.obj2StringPretty(orderInfo));
        }catch (Exception e){
            // 秒杀失败，重复秒杀
            log.info("user -> {} , goods -> {} 减库存,下订单,写入秒杀订单失败",user.getNickname(),goods.getId());
        }
    }

    private OrderInfo getMiaoshaOrderByUserIdGoodsId(Long userId , Long goodsId){
        OrderInfo order = JsonUtil.string2Obj(redisService.get(OrderKey.getSeckillOrderByYidGid,userId+"_"+goodsId),OrderInfo.class);
        return order;
    }


}
